package com.api.chatai.controller;

import com.api.chatai.domain.dtos.LoginDto;
import com.api.chatai.domain.dtos.RegisterDto;
import com.api.chatai.domain.pojo.User;
import com.api.chatai.domain.pojo.Result;
import com.api.chatai.service.UserService;
import com.api.chatai.ThreadLocal.UserContextHolder;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.api.chatai.utils.JwtHelper;
import java.util.HashMap;
import java.util.List;


@RestController
@RequestMapping("/user")
@Slf4j
@RequiredArgsConstructor
@Tag(name = "用户相关接口")
public class UserController {
    @Autowired
    private  UserService userService;

    @GetMapping
    @Operation(summary = "查询所有用户")
    public Result list() {
        log.info("查询用户列表");
        List<User> list = userService.list();
        return Result.success(list);
    }

    @PostMapping("/login")
    @Operation(summary = "用户登录")
    public Result login(@RequestBody LoginDto loginDto) {
        log.info("用户登录:{}", loginDto);
        String token = userService.login(loginDto);
        HashMap<String, String> map = new HashMap<>();
        map.put("token", token);
        return Result.success(map);
    }

    @GetMapping("/sendCode")
    @Operation(summary = "发送邮箱验证码")
    public Result sendCode(@RequestParam String email) {
        log.info("发送邮箱验证码:{}", email);
        userService.sendCode(email);
        return Result.success();
    }

    @PostMapping("/register")
    @Operation(summary = "用户注册")
    public Result register(@RequestBody RegisterDto registerDto) {
        log.info("用户注册:{}", registerDto);
        String token = userService.register(registerDto);
        HashMap<String, String> map = new HashMap<>();
        map.put("token", token);
        return Result.success(map);
    }

    @GetMapping("/info")
    @Operation(summary = "用户个人信息查询")
    public Result queryInfo() {
        log.info("用户个人信息查询");
        Integer id = UserContextHolder.getUser();
        User user = userService.getById(id);
        user.setPassword(null);
        return Result.success(user);
    }

}